package com.wildish.demo.dao.impl;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.wildish.demo.ebo.TestUser;

public class TestUserTxMapper {

	private PlatformTransactionManager pm;
	private JdbcTemplate jdbc;
	private SqlSession sqlSession;
	
	public void setTransactionManager(
			PlatformTransactionManager transactionManager) {
		this.pm = transactionManager;
	}

	public void setDataSource(DataSource ds) {
		this.jdbc = new JdbcTemplate(ds);
	}
	
	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}

	public void workWithTx() {
		TransactionDefinition def = new DefaultTransactionDefinition();
		TransactionStatus status = pm.getTransaction(def);

		try {
			// 事务操作
			String addRole = "insert into test_role(id, role_name) values (5, 'kubi')";
			String addUser = "insert into test_user(id, user_name, password, age) values (10, 'keith', 'dfaewklj', 29)";
			String addUserRole = "insert into test_user_role(user_id, role_id) values (10, 5)";
			jdbc.execute(addRole);
			jdbc.execute(addUser);
			jdbc.execute(addUserRole);
			
			pm.commit(status);
		} catch (Exception e) {
			pm.rollback(status);
			throw e;
		}
	}
	
	public TestUser workWithSqlSession() {
		return (TestUser) sqlSession.selectOne("com.wildish.demo.dao.TestUserMapper.selectWithRole", 1);
	}
}
